<?php

namespace App\Models\V1;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Lessons extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at'];
    protected $table = 'lessons';
    protected $fillable = ['title', 'lessons_category_id', 'video_url', 'user_id', 'introduce', 'video_img'];


    public function belongsToLessonsClassRoom()
    {
        return $this->belongsTo(LessonsClassRoom::class, 'lessons_category_id', 'id');
    }

    public function hasManyComment()
    {
        return $this->hasMany(Comment::class, 'lessons_id', 'id');
    }

    //获取视频的详细信息
    public function get_lessons_data($lessonId, $videoSuggestLength, $userPhone)
    {
        $comments_detail = DB::table('comments as c')
            ->select('c.*', 'm.FilePath1', 'm.YourName', 'mm.YourName as replyName')
            ->where('c.lessons_id', $lessonId)
            ->Join('memberinfo as m', 'c.user_id', '=', 'm.UserID')
            ->leftJoin('memberinfo as mm', 'c.replay_user_id', '=', 'mm.UserID')
            ->whereNull('c.deleted_at')
            ->where('type', '1')
            ->get()->toArray();

        foreach ($comments_detail as $k => $v) {
            $str       = substr($v->up_time_user, 1);
            $v->isLike = preg_match("/$userPhone/", $str) ? 1 : 0;//1为用户已经点赞了0为用户还没有点赞;
        }

        //判断用户是否已经点过赞了
//        foreach ($comments_detail as $key => $value) {
//            $user_phones = explode(',', $value->up_time_user);
//            unset($user_phones[0]);
//            if (in_array($userPhone, $user_phones)) {
//                $value->isLike = 1;//如果用户已经点过赞了为1
//            } else {
//                $value->isLike = 0;//如果用户没有点过赞为0
//            }
//        }
        $comments_detail = $this->comments_data($comments_detail);


        $lessons_detail = Lessons::find($lessonId)->toArray();

        if (!$lessons_detail) { //如果当前的课程已经被删除了,就返回一个空的数组
            return $lessons_detail = [];
        }
        $lessons_detail = DB::table('lessons')
            ->where('id', '=', $lessonId)
//            ->leftJoin('memberinfo as m', 'm.UserID', '=', 'lessons.user_id')
            ->select('lessons.*', 'lessons.user_id as YourName')
            ->first();
        //修改观看的次数
        $change_looking_times = Lessons::find($lessonId)->increment('looking_times');

        $tmp = [];
        foreach ($comments_detail as $k => $v) {
            $v->body = emoji_text_decode($v->body);
            $tmp[]   = json_decode(json_encode($v), true);
        }

        foreach ($tmp as $k => $v) {
            foreach ($v['sub_comments'] as $kk => $vv) {
                $tmp_sub[]               = $vv;
                $tmp[$k]['sub_comments'] = $tmp_sub;
            }
        }

        $lessons_detail = collect($lessons_detail)->toArray();

        $lessons_detail['has_many_comments'] = $tmp;

        $video_suggest = $this->video_suggest($videoSuggestLength);//推荐视频

        $share_url = [
            'title'     => $lessons_detail['title'],
            'share_img' => $lessons_detail['video_img'],
            'introduce' => $lessons_detail['introduce'],
            'url'       => url('/web/share/index', ['id' => $lessonId])
        ];

        $lessons_detail = array_merge(['lessons_comments_data' => $lessons_detail], ['suggest_video' => $video_suggest], ['share_url' => $share_url]);
        return $lessons_detail;
    }

    //修改评论数据的格式
    public function comments_data($comment_data)
    {
        $comments = [];

        //遍历构成父子结构
        foreach ($comment_data as $k => &$v) {
            //若用户头像为空则设置默认的用户头像
            $v->FilePath1 = change_member_head_img($v->FilePath1);

            //生成子级结构
            if ($v->pid == 0 && $v->deleted_at == null) {
                $v->sub_comments = $this->get_child_comemnt($comment_data, $v->id);
                array_push($comments, $v);
                unset($comment_data[$k]);
            }

        }
        return array_values($comments);
    }

    /**
     * @param $comments 评论的数据
     * @param $parentCommentId 评论者的父级ID
     * @return array
     */
    private function get_child_comemnt($comments, $parentCommentId)
    {
        $tempComments = [];
        foreach ($comments as $key => $comment) {
            if ($comment->pid == $parentCommentId) {
                if ($comment->deleted_at == null) { //没有删除
                    array_push($tempComments, $comment);
                }
                $tempComent = $comment;
                unset($comments[$key]);
                $childComents = $this->get_child_comemnt($comments, $tempComent->id);
                $tempComments = array_merge($tempComments, $childComents);
            }
        }
        return $tempComments;
    }

    /**
     * 获取推荐视频的信息
     * @param $videoSuggestLength 推荐视频的长度
     * @return mixed
     */
    public function video_suggest($videoSuggestLength)
    {
        //推荐视频信息
        $suggest_video = Lessons::orderBy('looking_times', 'desc')
            ->select(['id', 'title', 'lessons_category_id', 'video_url', 'video_img'])
            ->limit($videoSuggestLength)->get()->toArray();
        return $suggest_video;
    }


    //用户评论后返回子评论

    public function get_single_coment($commentId, $userId)
    {
        $userInfo = DB::table('memberinfo')->where('UserID', $userId)->first();

        $mobile = $userInfo->UserName;

        //顶级评论
        $topComment            = DB::table('comments as c')
            ->select('c.*', 'm.FilePath1', 'm.YourName', 'mm.YourName as replyName')
            ->Join('memberinfo as m', 'c.user_id', '=', 'm.UserID')
            ->leftJoin('memberinfo as mm', 'c.replay_user_id', '=', 'mm.UserID')
            ->where('id', $commentId)
            ->first();
        $topComment->FilePath1 = change_member_head_img($topComment->FilePath1);
        $topComment->isLike    = preg_match("/$mobile/", $topComment->up_time_user) ? 1 : 0;

        //子评论
        $subComments  = $this->get_child_coment($commentId);
        $subComments1 = [];
        foreach ($subComments as $key => $com) {
            if (!$com->deleted_at) {
                $com->isLike = preg_match("/$mobile/", $com->up_time_user) ? 1 : 0;
                array_push($subComments1, $com);
            }
            $com->FilePath1 = change_member_head_img($com->FilePath1);
        }
        sort($subComments1);
        $topComment->sub_comments = $subComments1;

        return $topComment;
    }


    //获取评论下的回复信息
    private function get_child_coment($pid)
    {
        $comments = [];
        $comment  = DB::table('comments as c')
            ->select('c.*', 'm.FilePath1', 'm.YourName', 'mm.YourName as replyName')
            ->Join('memberinfo as m', 'c.user_id', '=', 'm.UserID')
            ->leftJoin('memberinfo as mm', 'c.replay_user_id', '=', 'mm.UserID')
            ->where('pid', $pid)
            ->get()->toArray();

        if (count($comment) > 0) {
            $comments = array_merge($comments, $comment);
        }

        foreach ($comment as $com) {
            $pid      = $com->id;
            $comments = array_merge($comments, $this->get_child_coment($pid));
        }

        return $comments;
    }


    //去除保存的时候空白
    public function setIntroduceAttribute($data)
    {
        $this->attributes['introduce'] = trim($data);
    }

    //获取所有学习官的信息
    public function clo_info()
    {
        $data = DB::table('chapter_drp as cd')
            ->where('is_delete', 0)
            ->select('m.YourName', 'cd.user_id')
            ->leftJoin('memberinfo as m', 'm.UserID', '=', 'cd.user_id')
            ->get();
        return $data;
    }
}
